#pragma once
#include "Common.h"
#include "ThreadCache.h"
#include "PageCache.h"
#include"ObjPool.h"

static void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignSize = SizeClass::RoundUp(size);
		size_t kpage = alignSize >> PAGE_SHIFT;

		PageCache::GetInstance()->Lock();
		Span* span = PageCache::GetInstance()->NewSpan(kpage);
		span->_Objsize = size;	
		PageCache::GetInstance()->UnLock();

		void* ptr = (void*)(span->_pageId << PAGE_SHIFT);
		return ptr;
	}
	else
	{
		if (pTLSThreadCache == nullptr)
		{
			static ObjectPool<ThreadCache> TcPoll;
			pTLSThreadCache = TcPoll.New();
		}
		return pTLSThreadCache->Allocate(size);
	}
}

static void ConcurrentFree(void* ptr)
{
	Span* span = PageCache::GetInstance()->MapObjToSpan(ptr);
	size_t size = span->_Objsize;
	if (size > MAX_BYTES)
	{
	

		PageCache::GetInstance()->Lock();
		PageCache::GetInstance()->ReleaseSpantoPageCache(span);
		PageCache::GetInstance()->UnLock();
	}
	else
	{
		assert(ptr);
		pTLSThreadCache->Deallocate(ptr, size);
	}
}